﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SimpleMVC.Filters;
using SimpleMVC.Models;

namespace SimpleMVC.Controllers
{
    public class AccountController : Controller
    {
        [HttpGet,PRGModelState]
        public ActionResult Login()
        {
            return View();
        }

        [PRGModelState]
        public ActionResult Login(string name, string password)
        {
            if (ModelState.IsValid)
            {
                string[] roles = null;
                int userid = 0;
                if (Validate(name, password, out roles,out userid))
                {
                    Session["user"] = name;
                    Session["roles"] = roles;
                    Session["userid"] = userid;
                    Teacher teacher = new Teacher() {Name = "xsg",Age = -22};
                    Session["teacher"] = teacher;
                    return Redirect("~/Home/Index");
                }
                else
                {
                    ModelState.AddModelError("loginerror", "用户名或密码不正确");
                    return Redirect("Login");
                }
            }
            else
            {
                return Redirect("Login");
            }
        }

        private bool Validate(string user, string password, out string[] roles,out int userid)
        {
            if (string.Compare(user,"xsg",true)!=0|| string.Compare(password, "xsg", true) != 0)
            {
                roles = null;
                userid = 0;
                return false;
            }
            userid = 1;
            roles = new string[] {"guest"};
            return true;
        }
    }
}